﻿using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using AutoCADDotNetLibrary;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;

namespace Test
{
    public class XDataPaletteViewModel : IReadEntityEvent
    {
        public ObservableCollection<ObservableCollection<object>> Data { get; set; } = new ObservableCollection<ObservableCollection<object>>();

        private ObjectId _id;

        #region IReadEntityEvent

        public bool IsUseEvent { get; set; } = true;

        public void ReadEntities(Document doc, Entity[] ents)
        {
            if (ents != null && ents.Length == 1 && ents[0].XData != null)
            {
                _id = ents[0].Id;
                foreach (TypedValue item in ents[0].XData.Cast<TypedValue>())
                {
                    ObservableCollection<object> oc = new ObservableCollection<object>() { (int)item.TypeCode, item.Value };
                    Data.Add(oc);
                }
            }
            else
            {
                _id = ObjectId.Null;
                Data.Clear();
            }
        }

        #endregion

        public ICommand IsUseEventTrueCommand => new RelayCommand(() => this.IsUseEvent = true);

        public ICommand IsUseEventFalseCommand => new RelayCommand(() => this.IsUseEvent = false);

        public ICommand ChangeXDataCommand => new RelayCommand(() => SimpleAutoCADAOP.RunUIMethod(_changeXData, true));

        private void _changeXData(Document doc)
        {
            if (Application.DocumentManager.MdiActiveDocument.Database != _id.Database || !_id.IsValid)
            {
                ReadEntities(null, null);
                return;
            }

            Entity ent = _id.GetObject(OpenMode.ForWrite) as Entity;
            ResultBuffer xdata = new ResultBuffer(Data.Select(x => new TypedValue((int)x[0], x[1])).ToArray());
            ent.XData = xdata;
        }
    }
}
